package com.blue.spring.resource;

import java.util.Locale;
import java.util.TimeZone;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.i18n.LocaleContext;
import org.springframework.context.i18n.TimeZoneAwareLocaleContext;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.i18n.AbstractLocaleContextResolver;
import org.springframework.web.util.WebUtils;

public class SessionLocaleResolver extends AbstractLocaleContextResolver
{
	public static final String LOCALE_SESSION = "_SESSION_LOCALE_";
	public static final String TIME_ZONE_SESSION = "_SESSION_TIME_ZONE_";

	@Override
	public Locale resolveLocale(HttpServletRequest request)
	{
		Object object = WebUtils.getSessionAttribute(request, LOCALE_SESSION);
		if (object == null)
			return this.determineDefaultLocale(request);

		Locale locale = null;
		if (object instanceof String)
		{
			locale = StringUtils.parseLocaleString((String)object);
		}
		else if (object instanceof Locale)
		{
			locale = (Locale)object;
		}
		
		return locale;
	}
	
	public TimeZone resolveTimeZone(HttpServletRequest request)
	{
		Object object = WebUtils.getSessionAttribute(request, TIME_ZONE_SESSION);
		if (object == null)
			return this.getDefaultTimeZone();

		TimeZone timeZone = null;
		if (object instanceof String)
		{
			timeZone = StringUtils.parseTimeZoneString((String)object);
		}
		else if (object instanceof TimeZone)
		{
			timeZone = (TimeZone)object;
		}
		
		return timeZone;
	}

	@Override
	public LocaleContext resolveLocaleContext(final HttpServletRequest request)
	{
		return new TimeZoneAwareLocaleContext()
		{
			@Override
			public Locale getLocale()
			{
				return SessionLocaleResolver.this.resolveLocale(request);
			}

			@Override
			public TimeZone getTimeZone()
			{
				return SessionLocaleResolver.this.resolveTimeZone(request);
			}
		};
	}

	@Override
	public void setLocaleContext(HttpServletRequest request, HttpServletResponse response, LocaleContext localeContext)
	{
		Locale locale = null;
		TimeZone timeZone = null;
		if (localeContext != null)
		{
			locale = localeContext.getLocale();
			if (localeContext instanceof TimeZoneAwareLocaleContext)
			{
				timeZone = ((TimeZoneAwareLocaleContext)localeContext).getTimeZone();
			}
		}
		WebUtils.setSessionAttribute(request, LOCALE_SESSION, locale);
		WebUtils.setSessionAttribute(request, TIME_ZONE_SESSION, timeZone);
	}

	protected Locale determineDefaultLocale(HttpServletRequest request)
	{
		Locale defaultLocale = getDefaultLocale();
		if (defaultLocale == null)
		{
			defaultLocale = request.getLocale();
		}
		return defaultLocale;
	}
}
